package com.example.bysj.Controller;
//201902104061徐中堂
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.SQLException;
//捕捉异常
@ControllerAdvice
@Slf4j
public class MyExceptionController {
    public static final String DEFAULT_ERROR_VIEW = "error";
    @ExceptionHandler(Exception.class)
    public final ModelAndView handleAllExceptions(Exception ex, HttpServletRequest request, HttpServletResponse response){
        ModelAndView modelAndView = new ModelAndView();
        if (ex instanceof NullPointerException){
            log.error("代码00" + ex.getMessage(),ex);
            modelAndView.addObject("status",response.getStatus());
            modelAndView.addObject("msg", ex.getLocalizedMessage());
            modelAndView.addObject("url",request.getRequestURL());
            modelAndView.setViewName(DEFAULT_ERROR_VIEW);
        } else if (ex instanceof IllegalArgumentException){
            log.error("代码01" + ex.getMessage(),ex);
            modelAndView.addObject("status",response.getStatus());
            modelAndView.addObject("msg", "请求参数不匹配" + ex.getLocalizedMessage());
            modelAndView.addObject("url",request.getRequestURL());
            modelAndView.setViewName(DEFAULT_ERROR_VIEW);
        } else if (ex instanceof SQLException){
            log.error("代码01" + ex.getMessage(),ex);
            modelAndView.addObject("status",response.getStatus());
            modelAndView.addObject("msg", "数据库访问异常" + ex.getLocalizedMessage());
            modelAndView.addObject("url",request.getRequestURL());
            modelAndView.setViewName(DEFAULT_ERROR_VIEW);
        } else {
            log.error("代码99" + ex.getMessage(),ex);
            modelAndView.addObject("status",-1);
            modelAndView.addObject("msg",ex.getLocalizedMessage());
            modelAndView.addObject("url",request.getRequestURL());
            modelAndView.setViewName(DEFAULT_ERROR_VIEW);
        }
        return modelAndView;
    }
}
